<template>
  <div class="article-list-container">
    <el-card shadow="never" class="mb-5 border-box">
      <div class="filter-section">
      <div class="left-section">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索信息标题"
            class="search-input"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </div>
        <el-button type="primary" @click="toAddArticle">
          <el-icon>
            <Plus />
          </el-icon>
          发布信息
        </el-button>
      </div>
      <div class="filter-box">
        <el-radio-group v-model="strategyType" size="default" @change="strategyByType">
          <el-radio-button :label="1" :value="1">官网</el-radio-button>
          
        </el-radio-group>
      </div>
      </div>
    </el-card>
    <div class="page-content article-list">
      <div v-if="!showEmpty" class="list h-[calc(100vh-330px)] overflow-y-auto">
        <div class="offset">
          <div class="item attraction-card" v-for="item in articleList" :key="item.id" @click="toDetail(item)">
            <!-- 骨架屏 -->
            <el-skeleton animated :loading="isLoading" class="w-full h-full">
              <template #template>
                <div class="top">
                  <el-skeleton-item
                    variant="image"
                    style="width: 100%; height: 100%; border-radius: 10px"
                  />
                  <div style="padding: 16px 0">
                    <el-skeleton-item variant="p" style="width: 80%" />
                    <el-skeleton-item variant="p" style="width: 40%; margin-top: 10px" />
                  </div>
                </div>
              </template>

              <template #default>
                <!-- w-full h-full flex flex-col -->
                <div class="top w-full h-full flex flex-col">
                  <!-- <el-image class="cover" :src="item.messageShowImg" lazy fit="cover">
                    <template #error>
                      <div class="image-slot">
                        <el-icon><icon-picture /></el-icon>
                      </div>
                    </template>
                  </el-image> -->
                  <el-image
                      class="cover attraction-image w-full h-183px object-cover"
                      lazy
                      :src="item.messageShowImg"
                      fit="cover"
                    >
                      <template #error>
                        <div
                          class="image-slot flex justify-center items-center w-full h-full bg-fill-light text-text-secondary text-30px"
                        >
                          <el-icon>
                            <Picture />
                          </el-icon>
                        </div>
                      </template>
                    </el-image>
                  <span class="type" v-if="item.sendStatus">
                    {{ getStatus(item.sendStatus) }}
                  </span>
                </div>
                <div class="bottom">
                  <h2>{{ item.messageTitle }}</h2>
                  <div class="info">
                    <div class="text">
                      <i class="iconfont-sys">&#xe6f7;</i>
                      <span>{{ useDateFormat(item.sendTime, 'YYYY-MM-DD') }}</span>
                      <div class="line"></div>
                      <i class="iconfont-sys">&#xe689;</i>
                      <span>{{ item.browseCount }}</span>
                    </div>
                  
                
                    <!-- <el-button v-auth="'edit'" size="small" @click.stop="toEdit(item)"
                      >编辑</el-button
                    > -->
                  </div>
                  <div class="flex justify-end">
                      <el-button
                        type="primary"
                        text
                        size="small"
                        @click.stop="toEdit(item)"
                    >
                        <el-icon><Edit /></el-icon>编辑
                    </el-button>
                    
                    <el-button
                        v-if="item.sendStatus === 2"
                        type="danger"
                        text
                        size="small"
                        @click.stop="handleRevoke(item)"
                    >
                        <el-icon><Delete /></el-icon>撤销
                    </el-button>
                    <el-button
                        v-if="item.sendStatus === 3"
                        type="primary"
                        text
                        size="small"
                        @click.stop="handleRelease(item)"
                    >
                        <el-icon><Plus /></el-icon>发布
                    </el-button>
                    </div>
                </div>
              </template>
            </el-skeleton>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="flex justify-center h-[calc(100vh-308px)]" v-if="showEmpty">
        <el-empty description="暂无信息数据" />
      </div>

      <!-- 分页器 -->
      <div class="flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8, 16, 24, 32]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { Picture as IconPicture, Plus, Edit, Delete } from '@element-plus/icons-vue'
  import { ref, onMounted, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { useDateFormat } from '@vueuse/core'
  import { Search } from '@element-plus/icons-vue'
  import { scenicMessagePageMessageUsingPost, scenicMessageUpdateMessagePushUsingPost, scenicMessageGetMessageInfoByIdUsingPost,scenicMessageUpdateStatusUsingGet } from '@/api/4a'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { xiaoxivo } from '@/api/4a/types'

  const router = useRouter()
  const articleList = ref<xiaoxivo[]>([])
  const total = ref(0)
  const isLoading = ref(true)
  const currentPage = ref(1) // 当前页码
  const searchKeyword = ref('') // 搜索关键字
  const strategyType = ref(1) // 发布策略
  const sendStatus = ref(2) // 发布状态
  const pageSize = ref(8) // 每页条数
  // 请求参数
  const formData = ref({
    current: 1,
    like: '',
    messageAuthorId: undefined,
    sendStatus: 2,
    size: 8,
    strategyType: 1
  })

  // 获取信息列表
  const getArticleList = () => {
    isLoading.value = true
    try {
      formData.value.current = currentPage.value
      formData.value.like = searchKeyword.value
      formData.value.strategyType = strategyType.value
      formData.value.sendStatus = sendStatus.value
      scenicMessagePageMessageUsingPost({
        body: {
          current: currentPage.value,
          size: pageSize.value,
          like: searchKeyword.value,
          strategyType: strategyType.value
        }
      }).then((res) => {
        if (res.code === 0) {
          articleList.value = res.data?.list
          total.value = res.data?.total || 0
          isLoading.value = false
          articleList.value.forEach((item) => {
            item.messageShowImg = JSON.parse(item.messageShowImg)[0]?.path || '[]'
          })
        }
      })
    } catch (error) {
      console.error('获取信息列表失败', error)
      ElMessage.error('获取信息列表失败')
    } finally {
      isLoading.value = false
    }
  }

  const getStatus = (status) => {
    const statusMap = {
      1: '待发布',
      2: '已发布',
      3: '已撤稿',
      4: '已归档'
    }
    return statusMap[status] || '未知状态'
  }

  // 策略切换
  const strategyByType = () => {
    formData.value.strategyType = strategyType.value
    getArticleList()
  }

  onMounted(() => {
    getArticleList()
  })
  // 处理页码大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getArticleList()
  }
  // 分页切换
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getArticleList()
  }
  // 跳转详情
  const toDetail = (item) => {
    router.push({
      path: `/article/detail`,
      query: {
        id: item.id
      }
    })
  }

  // 编辑信息
  const toEdit = (item) => {
    router.push({
      path: `/article/article-publish`,
      query: {
        id: item.id
      }
    })
  }

  // 撤销信息
  const handleRevoke = (item: xiaoxivo) => {
    ElMessageBox.confirm(
      '确认要撤销该信息吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        // 只传id和sendStatus后端报错，因此先获取详情再进行全部撤销
        // scenicMessageGetMessageInfoByIdUsingPost({
        //   params: {
        //     messageId: item.id
        //   }
        // }).then((res:any) => {
        //   if(res.code === 0 ){
        //       scenicMessageUpdateMessagePushUsingPost({
        //     body: {
        //       // id: item.id,
        //       // sendStatus: 2 // 撤销状态
        //       ...res.data,
        //       sendStatus: 3
        //     }
        //   }).then((res) => {
        //     if (res.code === 0) {
        //       ElMessage.success('撤销成功')
        //       getArticleList() // 刷新列表
        //     } else {
        //       ElMessage.error(res.msg || '撤销失败')
        //     }
        //   })
        //   }
        // }){
          scenicMessageUpdateStatusUsingGet({
          params: {
            id: item.id,
            sendStatus: 3
          }
        }).then((res) => {
          if (res.code === 0) {
            ElMessage.success('撤销成功')
            getArticleList() // 刷新列表
          } else {
            ElMessage.error(res.msg || '撤销失败')
          }
        })
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 信息发布
  const handleRelease = (item: xiaoxivo) => {
    ElMessageBox.confirm(
      '确认要发布该信息吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        scenicMessageUpdateStatusUsingGet({
          params: {
            id: item.id,
            sendStatus: 2
          }
        }).then((res) => {
          if (res.code === 0) { 
            ElMessage.success('发布成功')
            getArticleList() // 刷新列表
          } else {
            ElMessage.error(res.msg || '发布失败')
          }
        })
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 搜索景点
  const handleSearch = () => {
    currentPage.value = 1
    getArticleList()
  }

  // 新增信息
  const toAddArticle = () => {
    router.push({
      path: `/article/article-publish`
    })
  }
  // 空状态判断
  const showEmpty = computed(() => {
    return articleList.value.length === 0 && !isLoading.value
  })

  // 监听路由变化
  onActivated(() => {
    getArticleList()
  })
</script>

<style lang="scss" scoped>
  .article-list-container {
    min-height: calc(100vh - 121px);
  }

  .filter-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 16px;
    // margin-bottom: 20px;
    // background: #fff;
    border-radius: 8px;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);
    // border: 1px solid var(--art-card-border) !important;
    .left-section {
      display: flex;
      gap: 16px;
      align-items: center;

      .search-box {
        width: 300px;

        .search-input {
          width: 100%;
        }
      }
    }

    .filter-box {
      .el-radio-group {
        display: flex;
        gap: 8px;
      }
    }
  }

  .article-list {
    .custom-segmented .el-segmented {
      height: 40px;
      padding: 6px;

      --el-border-radius-base: 8px;
    }

    .list {
      margin-top: 20px;

      .offset {
        display: flex;
        flex-wrap: wrap;
        width: calc(100% + 20px);

        .item {
          box-sizing: border-box;
          width: calc(25% - 20px);
          margin: 0 20px 20px 0;
          cursor: pointer;
          border: 1px solid var(--art-border-color);
          border-radius: calc(var(--custom-radius) / 2 + 2px) !important;

          // &:hover {
          //   .el-button {
          //     opacity: 1 !important;
          //   }
          // }

          .top {
            position: relative;
            // aspect-ratio: 16/7.5;

            .cover {
              display: flex;
              align-items: center;
              justify-content: center;
              // width: 100%;
              // height: 100%;
              // object-fit: cover;
              background: var(--art-gray-200);
              border-radius: calc(var(--custom-radius) / 2 + 2px)
                calc(var(--custom-radius) / 2 + 2px) 0 0;

              // .image-slot {
              //   font-size: 26px;
              //   color: var(--art-gray-400);
              // }
            }

            .type {
              position: absolute;
              top: 5px;
              right: 5px;
              padding: 5px 4px;
              font-size: 12px;
              color: rgba(#fff, 0.8);
              background: rgba($color: #000, $alpha: 60%);
              border-radius: 4px;
            }
          }

          .bottom {
            padding: 5px 10px;

            h2 {
              font-size: 16px;
              font-weight: 500;
              color: #333;

              @include ellipsis();
            }

            .info {
              display: flex;
              justify-content: space-between;
              width: 100%;
              height: 25px;
              margin-top: 6px;
              line-height: 25px;

              .text {
                display: flex;
                align-items: center;
                color: var(--art-text-gray-600);

                i {
                  margin-right: 5px;
                  font-size: 14px;
                }

                span {
                  font-size: 13px;
                  color: var(--art-gray-600);
                }

                .line {
                  width: 1px;
                  height: 12px;
                  margin: 0 15px;
                  background-color: var(--art-border-dashed-color);
                }
              }

              .el-button {
                margin-left: 8px;  // Add some spacing between buttons
              }
            }
          }
        }
      }
    }
  }

  .border-box {
    border-radius: 8px !important;
  }

  @media only screen and (max-width: $device-notebook) {
    .article-list {
      .list {
        .offset {
          .item {
            width: calc(25% - 20px);
          }
        }
      }
    }
  }

  @media only screen and (max-width: $device-ipad-pro) {
    .article-list {
      .list {
        .offset {
          .item {
            width: calc(33.333% - 20px);

            .bottom {
              h2 {
                font-size: 16px;
              }
            }
          }
        }
      }
    }
  }

  @media only screen and (max-width: $device-ipad) {
    .article-list {
      .list {
        .offset {
          .item {
            width: calc(50% - 20px);
          }
        }
      }
    }
  }

  @media only screen and (max-width: $device-phone) {
    .article-list {
      .list {
        .offset {
          .item {
            width: calc(100% - 20px);
          }
        }
      }
    }
  }
  .attraction-card {
      height: 100%;
      transition: transform 0.3s;

      &:hover {
          transform: translateY(-5px);

          @apply shadow-lg shadow-black/5;
      }
  }
</style>
